package fr.waitandsee.fragments;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import fr.waitandsee.FragmentController;
import fr.waitandsee.R;
import fr.waitandsee.customwidgets.wheel.WheelView;
import fr.waitandsee.customwidgets.wheel.adapters.AbstractWheelTextAdapter;
import fr.waitandsee.customwidgets.wheel.adapters.ArrayWheelAdapter;
import fr.waitandsee.customwidgets.wheel.adapters.NumericWheelAdapter;

public class MediaEnrichmentFragment extends Fragment implements PageFragmentModel {
	
	private static final String TAG = "MediaEnrichmentFragment";
	
	private FragmentController fragmentController;
	
	private ImageView ivSave;
	private TextView tvValidate;
	private EditText etComment;
	private WheelView wvDay;
	private WheelView wvHours;
	private WheelView wvMins;
	private WheelView wvAMPM;
	
	public static MediaEnrichmentFragment newInstance(/*parameters*/) {
		MediaEnrichmentFragment fragment = new MediaEnrichmentFragment();
		// set parameters if needed : 
	    // Bundle bundle = new Bundle(1);
	    // bundle.putInt(EXTRA_NAME, param);
	    // fragment.setArguments(bundle);
	    return fragment ;
	}
	
	
	  /////////////////////////
	 // FRAGMENT LIFE CYCLE //
	/////////////////////////
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate.savedInstanceState="+savedInstanceState);
		this.fragmentController = (FragmentController) getActivity();
	}
	
 	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 		Log.d(TAG, "onCreateView.savedInstanceState="+savedInstanceState);
		if (savedInstanceState != null) {
			// get saved parameters if needed : 
			// param = savedInstanceState.getInt(EXTRA_NAME);
		} else {
			if(getArguments() != null) {
				// get parameters if needed :
				// param = getArguments().getInt(EXTRA_NAME);
			}
		}
		View v = inflater.inflate(R.layout.fragment_media_enrichment, container, false);
		return v;
	}
	
 	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
 		Log.d(TAG, "onViewCreated.savedInstanceState="+savedInstanceState);
		fetchViews();
		customizeViews();
		setListeners();
	}
 	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		Log.d(TAG, "onSaveInstanceState.outState="+outState);
		super.onSaveInstanceState(outState);
		// save parameters if needed :
		// outState.putInt(EXTRA_NAME, param);
	}
 	
	@Override
 	public void fetchViews() {
		this.ivSave = (ImageView) getView().findViewById(R.id.imageView_head_save);
		this.tvValidate = (TextView) getView().findViewById(R.id.textView_validate);
		this.etComment = (EditText) getView().findViewById(R.id.editText_comment);
		this.wvDay = (WheelView) getView().findViewById(R.id.wheelView_day);
		this.wvHours = (WheelView) getView().findViewById(R.id.wheelView_hours);
		this.wvMins = (WheelView) getView().findViewById(R.id.wheelView_mins);
		this.wvAMPM = (WheelView) getView().findViewById(R.id.wheelView_ampm);
 	}
	
	@Override
	public void customizeViews() {
		Calendar calendar = Calendar.getInstance(Locale.US);
	    // wheelview "day"
        wvDay.setViewAdapter(new DayArrayAdapter(getActivity(), calendar));
		// wheelview "hours"
        NumericWheelAdapter hourAdapter = new NumericWheelAdapter(getActivity(), 0, 23);
        hourAdapter.setItemResource(R.layout.wheel_text_item);
        hourAdapter.setItemTextResource(R.id.text);
        wvHours.setViewAdapter(hourAdapter);
        wvHours.setCurrentItem(calendar.get(Calendar.HOUR));
        // wheelview "mins"
        NumericWheelAdapter minAdapter = new NumericWheelAdapter(getActivity(), 0, 59, "%02d");
        minAdapter.setItemResource(R.layout.wheel_text_item);
        minAdapter.setItemTextResource(R.id.text);
        wvMins.setViewAdapter(minAdapter);
        wvMins.setCurrentItem(calendar.get(Calendar.MINUTE));
        // wheelview "AP-PM"
        ArrayWheelAdapter<String> ampmAdapter = new ArrayWheelAdapter<String>(getActivity(), new String[] {getActivity().getString(R.string.AM), getActivity().getString(R.string.PM)});
	    ampmAdapter.setItemResource(R.layout.wheel_text_item);
	    ampmAdapter.setItemTextResource(R.id.text);
	    wvAMPM.setViewAdapter(ampmAdapter);
	    wvAMPM.setCurrentItem(calendar.get(Calendar.AM_PM));
	}
 	
	@Override
	public void setListeners() {
		this.ivSave.setOnClickListener(onSaveClickListener);
		this.tvValidate.setOnTouchListener(onValidateTouchListener);
 	}
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
 	
 	private OnClickListener onSaveClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Log.i(TAG, "onSaveClickListener");
			//TODO action on "Save" button clicked
		}
	};
	
	private OnTouchListener onValidateTouchListener = new OnTouchListener() {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			Log.i(TAG, "onValidateTouchListener");
			tvValidate.setOnTouchListener(null); // stand-by listener to prevent multi openning
			String comment = etComment.getText().toString(); 					//DEBUG
			int day = wvDay.getCurrentItem();									//DEBUG
			int hours = wvHours.getCurrentItem();								//DEBUG
			int mins = wvMins.getCurrentItem();									//DEBUG
			int ampm = wvAMPM.getCurrentItem();									//DEBUG
			Log.d(TAG, "comment="+comment+", day="+day+", hours="+hours			//DEBUG
											+", mins="+mins+", ampm="+ampm); 	//DEBUG
			//TODO action on "Validate" button clicked
			fragmentController.switchContent(HomeFragment.newInstance());
			return false;
		}
	};
	
	
	  ///////////////////////////
	 // CUSTOMIZED DATEPICKER //
	///////////////////////////
	
    private class DayArrayAdapter extends AbstractWheelTextAdapter {
        // Count of days to be shown
        private final int daysCount = 365;
        // Calendar
        private Calendar calendar;
        
        protected DayArrayAdapter(Context context, Calendar calendar) {
            super(context, R.layout.custom_date_picker_day, NO_RESOURCE);
            this.calendar = calendar;
            setItemTextResource(R.id.time2_monthday);
        }

        @Override
        public View getItem(int index, View cachedView, ViewGroup parent) {
            int day = index;
            Calendar newCalendar = (Calendar) calendar.clone();
            newCalendar.roll(Calendar.DAY_OF_YEAR, day);
            
            View view = super.getItem(index, cachedView, parent);
            TextView weekday = (TextView) view.findViewById(R.id.time2_weekday);
            if (day == 0) {
                weekday.setText("");
            } else {
                DateFormat format = new SimpleDateFormat("EEE", Locale.US);
                weekday.setText(format.format(newCalendar.getTime()));
            }

            TextView monthday = (TextView) view.findViewById(R.id.time2_monthday);
            if (day == 0) {
                monthday.setText("Today");
                monthday.setTextColor(0xFF0000F0);
            } else {
                DateFormat format = new SimpleDateFormat("MMM d", Locale.US);
                monthday.setText(format.format(newCalendar.getTime()));
                monthday.setTextColor(0xFF111111);
            }

            return view;
        }
        
        @Override
        public int getItemsCount() {
            return daysCount+1;
        }
        
        @Override
        protected CharSequence getItemText(int index) {
            return "";
        }
    }

}
